import React, { Component } from 'react';
import {
  NativeModules,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
  Keyboard,
  View,
} from 'react-native';
import { isAndroid, px2dp, screenWidth, mainBgColorWhite, mainBgColorLightGray } from '@/styles';
import { uploadImage, uploadVoice } from '@/config';
import { msg, ValidConst, Button } from '@/common';
import api from '@/api';
import WordBox from './components/word-box';
import PictureBox from './components/picture-box';
import VoiceBox from './components/voice-box';
import ContractBox from './components/contract-box';

const { Submit } = Button;

export default class UserFeedback extends Component {
  constructor(props) {
    super(props);
    this.state = {
      blurBool: false,
      feedbackWord: '',
      imageList: [],
      voiceList: [],
      name: '',
      mobile: '',
      checked: false,
      keyboardHeight: 0,
      isUploading: false,
    };
  }

  render() {
    const {
      blurBool,
      imageList,
      voiceList,
      checked,
      keyboardHeight,
    } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView
          ref='scroll'
          showsVerticalScrollIndicator={false}
          style={{ marginBottom: px2dp(176), }}
        >
          <WordBox onChangeText={this.onChangeText} />
          <PictureBox
            imageList={imageList}
            uploadImage={this.addImage}
            delImage={this.delImage}
          />
          <VoiceBox
            voiceList={voiceList}
            addVoice={this.addVoice}
            delVoice={this.delVoice}
          />
          <ContractBox
            checked={checked}
            switchChecked={this.switchChecked}
            onChangeContract={this.onChangeContract}
            keyboardHeight={keyboardHeight}
          />

        </ScrollView>
        <View style={styles.submitBoxWrap}>

          <Submit
            text='提交'
            boxStyle={{
              width: px2dp(590),
              height: px2dp(88),
              borderRadius: px2dp(44),
              marginTop: px2dp(16)
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(32),
            }}
            onClick={() => { this.submit(); }}
          />
        </View>
      </SafeAreaView>
    );
  }

  componentDidMount() {

  }

  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  // 提交
  submit = () => {
    const {
      feedbackWord,
      imageList,
      voiceList,
      name,
      mobile,
      checked,
      isUploading,
    } = this.state;
    if (isUploading) {
      msg.emit('app:tip', { text: '正在处理语音，请稍等' });
      return;
    }
    if (!feedbackWord && imageList.length <= 0 && voiceList.length <= 0) {
      msg.emit('app:tip', { text: '您没有输入任何内容！' });
      return;
    }
    if (!checked && !name && mobile.length < 11) {
      msg.emit('app:tip', { text: '如需匿名提交建议，请勾选下方【匿名反馈】' });
      return;
    }
    if (!checked && !ValidConst.phone.test(mobile)) {
      msg.emit('app:tip', { text: '手机号格式不正确' });
      return;
    }
    let newVoiceList = [];
    voiceList.map((item, index) => {
      newVoiceList.push(item.voiceUrl);
    });
    let params = {
      type: '1',
      content: feedbackWord,
      imgUrl: imageList,
      voiceUrl: newVoiceList,
    };
    if (!checked) {
      params.type = '2';
      params.userName = name;
      params.mobile = mobile;
    }

    api.user.addUserFeedback(params).then((res) => {
      if (res.success) {
        msg.emit('app:tip', { text: '提交成功' });
        this.timer = setTimeout(() => {
          msg.emit('router: back');
        }, 2000);
      } else {
        msg.emit('app:tip', { text: '提交失败' });
      }
    });
  };

  onChangeContract = (type, value) => {
    this.setState({ [type]: value });
  };

  switchChecked = () => {
    const { checked } = this.state;
    this.setState({ checked: !checked });
  };

  onChangeText = (text) => {
    this.setState({ feedbackWord: text });
  };

  // 删除图片
  delImage = (curIndex) => {
    const { imageList } = this.state;
    imageList.splice(curIndex, 1);
    this.setState({ imageList });
  };

  // 添加图片
  addImage = () => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.upload(path);
    });
  };

  // 上传照片
  upload(path) {
    const { imageList } = this.state;
    NativeModules.WindowModule.showLoading();
    uploadImage('upload?dirName=userFeedback', path)
      .then((res) => {
        if (res.success) {
          imageList.push(res.data.localId);
          this.setState({ imageList });
        } else {
          msg.emit('app:tip', { text: '上传失败，请重试' });
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        NativeModules.WindowModule.dismissLoading();
        msg.emit('app:tip', { text: '上传出错，请重试' });
      });
  }

  // 删除语音
  delVoice = (curIndex) => {
    const { voiceList } = this.state;
    voiceList.splice(curIndex, 1);
    this.setState({ voiceList });
  };

  // 上传语音到oss
  addVoice = (localVoice, voiceLen) => {
    const { voiceList } = this.state;
    this.setState({ isUploading: true });
    uploadVoice('upload?dirName=userFeedback', `file://${localVoice}`).then(
      (res) => {
        if (res.success) {
          const voiceUrl = res.data && res.data.localId;
          voiceList.push({ localVoice, voiceUrl, voiceLen });
          this.setState({ voiceList, isUploading: false });
        } else {
          msg.emit('app:tip', { text: '语音发送失败，请重试' });
        }
      },
    );
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  submitBoxWrap: {
    width: screenWidth,
    height: px2dp(176),
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    alignItems: 'center',

  }
});
